package com.zem.imos.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zem.imos.Entity.Admin;
import com.zem.imos.Entity.RespEntity;
import com.zem.imos.Mapper.AdminMapper;
import com.zem.imos.Service.AdminService;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //不拦截的路径
        List<String> asList = Arrays.asList("/userlogin", "/workerslogin" , "/imos/userlogin" , "/imos/workerslogin", "/imos/adminlogin", "/adminlogin","/userlogon","/imos/userlogon","/doctorlogon","/imos/doctorlogon","/adminlogon","/imos/adminlogon");
        String uri = request.getRequestURI();
        if(asList.contains(uri)){
            return true;
        }

        // 写好拦截的返回json 因为此处response不会自动解析实体为json
        response.setContentType("text/html;charset=UTF-8");
        RespEntity res = new RespEntity(RespEntity.ERespCode.AuthReject,uri);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(res));



        String token = request.getHeader("token");
        if(token==null){
            response.getWriter().println();
            return false;
        }

        //如果有token 解析token
        Claims claims = JWT.parseJwt(token);
        if(claims == null)
        {
            response.getWriter().println(jsonObject);
            return false;
        }

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        // 判断token是否过期
        if(claims.getExpiration().compareTo(now) == 1)
        {
            return true;
        }

        else
        {
            response.getWriter().println(jsonObject);
            return false;
        }


    }
}
